package com.codez.unionpay.guava.recursion;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.util.ObjectUtils;

import com.codez.util.JsonUtils;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

/**
 * 
 * @author 干净的代码
 * @创建时间  ： 2019-07-01
 * 
 */

public class RecursionTree {
	
	private static final String ROOT_LEVEL = "0";
	
	/**
	 *      权限项目中实现tree递归的简单逻辑
	 */
	
	public static void main(String[] args) {
		List<TreeNode> nodes = new ArrayList<>();
		nodes.add(new TreeNode(1,"0","系统管理",0));
		//nodes.add(new TreeNode(2,"0","交易管理",0));
		nodes.add(new TreeNode(3,"0.1","用户管理",1));
		nodes.add(new TreeNode(4,"0.1","角色管理",1));
		nodes.add(new TreeNode(5,"0.1","权限管理",1));
			

		nodes.add(new TreeNode(31,"0.1.3","用户管理1",3));
		nodes.add(new TreeNode(32,"0.1.3","用户管理2",3));
		nodes.add(new TreeNode(33,"0.1.3","用户管理3",3));
		
		nodes.add(new TreeNode(331,"0.1.3.33","用户管理31",33));
		
		// 根据上面的列表获取出tree
		List<TreeNode> root = new ArrayList<>();
		Multimap<String, TreeNode> multimap = ArrayListMultimap.create();
		Multimap<Integer, TreeNode> mapByPid = ArrayListMultimap.create();
		for (TreeNode node : nodes) {
			if(ROOT_LEVEL.equals(node.getLevel())) {
				root.add(node);
			}
			multimap.put(node.getLevel(), node);
			mapByPid.put(node.getPid(), node);
			
		}
		System.out.println(root);
//		loadChildren(root, multimap);
		loadChildrenByPid(root, mapByPid);
		System.out.println(JsonUtils.objectToJson(root));
		
	}
	
	// 各个节点主动递归加载自己的子节点
	public static void loadChildren(Collection<TreeNode> nodes , Multimap<String, TreeNode> map) {
		if(ObjectUtils.isEmpty(nodes)) {
			return;
		}
		for (TreeNode node : nodes) {
			Collection<TreeNode> children = map.get(node.getLevel() + "." + node.getId());
			if(!children.isEmpty()) {
				node.setChildren((List<TreeNode>) children);
				loadChildren(children ,map);
			}
		}
	}
	
	public static void loadChildrenByPid(Collection<TreeNode> nodes , Multimap<Integer, TreeNode> map) {
		if(ObjectUtils.isEmpty(nodes)) {
			return;
		}
		for (TreeNode node : nodes) {
			Collection<TreeNode> children = map.get(node.getId());
			if(!children.isEmpty()) {
				node.setChildren((List<TreeNode>) children);
				loadChildrenByPid(children ,map);
			}
		}
	}
	
}
